package com.YOTO.httpstaticserver.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.List;

@Configuration
public class StaticResourceConfig implements WebMvcConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(StaticResourceConfig.class);
    private final String uploadDir = "upload-dir";

    public StaticResourceConfig() {
        File directory = new File(uploadDir);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:" + uploadDir + "/")
                .setCachePeriod(0)
                .resourceChain(true)
                .addResolver(new ResourceResolver() {
                    @Override
                    public Resource resolveResource(HttpServletRequest request, String requestPath,
                                                 List<? extends Resource> locations,
                                                 ResourceResolverChain chain) {
                        String clientIp = getClientIp(request);
                        logger.info("访问IP: {} - 请求路径: {}", clientIp, requestPath);
                        
                        Resource resource = chain.resolveResource(request, requestPath, locations);
                        if (resource != null) {
                            return new ForceDownloadResource(resource);
                        }
                        return null;
                    }

                    @Override
                    public String resolveUrlPath(String resourcePath, List<? extends Resource> locations,
                                               ResourceResolverChain chain) {
                        return chain.resolveUrlPath(resourcePath, locations);
                    }
                });
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new DownloadInterceptor())
                .addPathPatterns("/files/**");
        
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/upload")
                .excludePathPatterns("/login", "/files/**", "/", "/css/**", "/js/**");
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    // 自定义Resource包装类，用于强制下载
    private static class ForceDownloadResource implements Resource {
        private final Resource resource;

        public ForceDownloadResource(Resource resource) {
            this.resource = resource;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return resource.getInputStream();
        }

        @Override
        public boolean exists() {
            return resource.exists();
        }

        @Override
        public URL getURL() throws IOException {
            return resource.getURL();
        }

        @Override
        public URI getURI() throws IOException {
            return resource.getURI();
        }

        @Override
        public File getFile() throws IOException {
            return resource.getFile();
        }

        @Override
        public long contentLength() throws IOException {
            return resource.contentLength();
        }

        @Override
        public long lastModified() throws IOException {
            return resource.lastModified();
        }

        @Override
        public Resource createRelative(String relativePath) throws IOException {
            return resource.createRelative(relativePath);
        }

        @Override
        public String getFilename() {
            return resource.getFilename();
        }

        @Override
        public String getDescription() {
            return resource.getDescription();
        }

        // 添加自定义的HTTP头，强制下载
        public String getContentDisposition() {
            return "attachment; filename=\"" + getFilename() + "\"";
        }
    }
} 